package iec104_master_connector

import (
	"encoding/json"
	"go-iot-gateway/internal/channel"
	channel_define "go-iot-gateway/internal/channel/define"
	conf_table_define "go-iot-gateway/internal/conf_table/define"
	"go-iot-gateway/internal/logger"
	iec104_client "go-iot-gateway/pkg/iec104/client"
	"strconv"
	"strings"
)

func NewIec104MasterConnector(channelConfig conf_table_define.ChannelInfo, protocolConfInfos []*conf_table_define.ProtocolInfo) (channel_define.ConnectChannel, error) {
	//todo 协议配置
	//todo 验证通道的有效性
	manager := channel.Manager()

	chl := &Iec104MasterChannel{}
	chl.channelManager = manager
	//chl.ProtocolConf = protocol //如果没有指定协议，使用默认
	chl.ChannelInfo = channel_define.ChannelInfo{}
	chl.isClosed = false
	chl.ChannelInfo.ChlId = channelConfig.Chl_id
	chl.ChannelInfo.Name = channelConfig.Chl_name
	chl.ChannelInfo.Addr = channelConfig.Chl_addr
	chl.ChannelInfo.Desc = channelConfig.Chl_desc
	chl.ChannelInfo.Protocol = channelConfig.Chl_protocol
	chl.ChannelInfo.SetStatus(channel_define.CONNECT_STATUS_CREATE, "已创建")
	chl.ChannelInfo.ChannelType = channelConfig.Chl_type
	chl.ChannelInfo.ProtocolType = channelConfig.Protocol_type
	chl.ChannelInfo.Frequency = channelConfig.Chl_colt_freq
	chl.ChannelInfo.WaitTime = channelConfig.Chl_wait_time
	connectParams := channel_define.ConnectParams{}
	err := json.Unmarshal([]byte(channelConfig.Chl_main_param), &connectParams)
	if err != nil {
		return nil, err
	}
	chl.ChannelInfo.ConnectParams = connectParams
	chl.logger = logger.NewChannelLogger(channelConfig.Chl_name)

	clientOptions := iec104_client.NewClientOptions()
	clientOptions.Address = strings.TrimSpace(connectParams.IpAddr) + ":" + strconv.Itoa(int(connectParams.Port))
	clientOptions.Logger = chl.logger
	clientOptions.OnConnectionLost = chl.onConnectionLost
	clientOptions.OnConnect = chl.onConnect
	clientOptions.OnMessageHandler = chl.onMessageHandler
	chl.iec104Client = iec104_client.NewClient(clientOptions)

	return chl, nil
}
